--[[
描述 ： UILayout
时间 ： 2014-8-25
]]
UILayout = {};
UILayout.rootWidth   = AW(320);
UILayout.rootHeight   = AH(460);
UILayout.defaultHeight  = AW(100);
UILayout.defaultWidth   = AW(100);
UILayout.defaultHeight  = AW(100);
UILayout.tbInterval     = AW(10);   -- 上下间隔
UILayout.lrInterval     = AW(10);    -- 左右间隔
UILayout.viewCtrl       = nil;        --储存数据的viewCtrl
UILayout.parentCtrl     = 1;        --创建布局的viewCtrl

--[[
描述：childValue    控件的w、h字段
FValue        父视图的大小
返回：        ‘%’等转换后的实际值
]]
function UILayout.getRealityValue( childValue , FValue ,isAllowStretch)   -- UILayout.getRealityValue(v.ml, width);
  if isAllowStretch ~= nil and isAllowStretch  then  --可拉伸
    if type(childValue) == 'string' then
      local str = string.sub(childValue, string.len(childValue), string.len(childValue));
      if string.byte(str) == 37 then
        --百分比转换
        str = string.sub(childValue, 1, string.len(childValue)-1);
        return tonumber(str)/100 * FValue;
      else
        return  UILayout.AH(tonumber(childValue));
      end
  else
    return UILayout.AH(childValue);
  end

else
  if type(childValue) == 'string' then
    local str = string.sub(childValue, string.len(childValue), string.len(childValue));
    if string.byte(str) == 37 then
      --百分比转换
      str = string.sub(childValue, 1, string.len(childValue)-1);
      return tonumber(str)/100 * FValue;
    else
      return  AW(tonumber(childValue));
    end
  else
    return AW(childValue);
  end
end
end

--[[
描述：根据根view的高度 算出空间的比例高度
height       空间高度
返回：        ‘%’等转换后的实际值
]]
function UILayout.AH( height )   -- UILayout.getRealityValue(v.ml, width);
  return math.ceil(height*UILayout.rootHeight/UIConfig.SCREEN_BASE_HEIGHT);     -- 以宽度为基准
end

----[[
--描述：childValue    控件的w、h字段
--FValue        父视图的大小
--返回：        ‘%’等转换后的实际值
--]]
--function UILayout.getRealityValueH( childValue , FValue )   -- UILayout.getRealityValue(v.ml, width);
--  if type(childValue) == 'string' then
--    local str = string.sub(childValue, string.len(childValue), string.len(childValue));
--    if string.byte(str) == 37 then
--      --百分比转换
--      str = string.sub(childValue, 1, string.len(childValue)-1);
--      return tonumber(str)/100 * FValue;
--    else
--      return UILayout.AH(tonumber(childValue));
--    end
--else
--  return UILayout.AH(childValue);
--end
--end



--[[
描述：计算W方向值
v       当前view的布局字典
width   父视图宽度
layout  布局方式
注：    不考虑isEqualTo...
]]
function UILayout.calW(v, width, layout)   --UILayout.calW(v, width, layout.layout);
  local w;
  if v.width then
    w = UILayout.getRealityValue(v.width, width);
  else
    if layout == 'h' then --横向布局
      if #v.items == 1 then --只有一个view
        if v.ml and v.mr then --没有width，有ml、mr，则:父-ml-mr
          w = width - UILayout.getRealityValue(v.ml, width) - UILayout.getRealityValue(v.mr, width);
      else
        w = UILayout.defaultWidth;
      end
    else
      w = UILayout.defaultWidth;
    end
    elseif layout == 'v' then --纵向布局
      if v.ml and v.mr then --没有width，有ml、mr，则:父-ml-mr
        w = width - UILayout.getRealityValue(v.ml, width) - UILayout.getRealityValue(v.mr, width);
    else
      w = UILayout.defaultWidth;
    end
    else --原点布局
      w = UILayout.defaultWidth;
    end
  end
  return w;
end

--[[
描述：计算H方向值
v       当前view的布局字典
width   父视图宽度
layout  布局方式
注：    不考虑isEqualTo...
]]
function UILayout.calH(v, height, layout, isAllowStretch)
  local h;
  if v.height then
    h = UILayout.getRealityValue(v.height, height,isAllowStretch);
  else
    if layout == 'h' then --横向布局
      if v.mt and v.mb then --没有height，有mt、mb，则：父-mt-mb
        h = height - UILayout.getRealityValue(v.mt, height,isAllowStretch)- UILayout.getRealityValue(v.mb, height,isAllowStretch);
    else
      h = UILayout.defaultHeight;
    end
    elseif layout == 'v' then --纵向布局
      if #v.items == 1 then --只有一个view
        if v.mt and v.mb then --没有height，有mt、mb，则:父-mt-mb
          h = height - UILayout.getRealityValue(v.mt, height,isAllowStretch) - UILayout.getRealityValue(v.mb, height,isAllowStretch);
      else
        h = UILayout.defaultHeight;
      end
    else
      h = UILayout.defaultHeight;
    end
    else --原点布局
      h = UILayout.defaultHeight;
    end
  end
  return h;
end

--[[
功能：   基础操作初始化
参数：   viewCtrl  所在viewCtrl
返回：   无
注解：   对于页面布局没影响，只是无法获取控件信息
]]
function UILayout:init( )
-- print('UILayout:init');

--  if  self.weekTable.viewcash == nil then
--    self.weekTable.viewcash = {};
--  end
end


------------------------------前端调用方法-------------------------

--[[
描述 ： x循环判断是否含有headView
参数 ： layout   --  布局 json文件
rootView -- 根view
返回 ： 无
]]
function UILayout.isHeadView(layout)
  for i, v in ipairs(layout.items) do
    if v.type  == 'UIHeadView' then
      return 1
    else
      local view = UILayout.genCtrl111(v);
    end
  end
end

function UILayout.genCtrl111(v)
  if  v.items~= nil and  #v.items > 0 then
    local layoutView = UILayout.isHeadView( v );
    return layoutView;
  end
  if v.type == 'UIHeadView' then
    return 1      --如果布局里面自己设置了headView 则返回1
  end
end

--[[
描述 ： 解析JSon文件
参数 ： layout   --  布局 json文件
rootView -- 根view
返回 ： 
]]
function UILayout.parseJson(jsonfile, width, height, viewCtrl )
  UILayout.isAllowStretch = true ;
  --print('wwwwwwwwparseJson===',width,height,UILayout.rootHeight)
  if width == nil or  width =='defult' then   --如果传的参数为nil或者defult 则传默认值
    width = AW(320) ;
  elseif height == nil or  height =='defult' then
    height = AH(460) ;
  end
  --UILayout.rootHeight = height ;

  local jsoninfo = MLFile.readFile('res/layout/'..jsonfile..'.layout');
  local layout = MLNative.json(jsoninfo);
  if layout then

    local  h = 0 ;
    local  num = 0 ;
    UILayout.infoList = {};
    UILayout.addHeight = 0 ;
    if layout.items and #layout.items > 0 then
      for i, v in ipairs(layout.items) do
        if v.type == "UILayout" then
          if  v.isAllowStretch  then    --如果是view并且是可以拉伸的
            --print('wwwwiddddddddddddd===',v.id,num)
            table.insert(UILayout.infoList,v.id);
            num = num + 1 ;
          else
            h = h + v.height ;
          end
        end
        if i == #layout.items then
          if h ~= 0 and num ~= 0 then
            UILayout.addHeight = (UILayout.AH(h) - AW(h))/num ;
          end
        end
      end
    end

    --print('addHeightpppppp============',UILayout.addHeight)
    local view = UILayout.parse(layout, width, height, viewCtrl )
    return view ;
  else
    print('json 不存在~~~~~~~~~~~')
    return
  end

end

--[[
描述 ： 循环遍历解析Json的根节点 算出宽高以及XY轴
参数 ： layout   -- json文件
      width -- 根view的宽度
      height -- 根view的高度
      viewCtrl --所在的view视图
返回 ： 
]]
function UILayout.parse(layout, width, height, viewCtrl)
  --print('UILayout.parse()self---------------',viewCtrl)
  if layout == nil then return end     --如果为nil则结束

  local layoutView = MLView.new():initView(width, height,viewCtrl,layout.id);

  --颜色 & 背景
  if layout.color then
    layoutView:setColor(tonumber(layout.color));
  end
  if layout.image and layout.image ~= '' then
    layoutView:setBg(UIImage.imageName(layout.image));
  end

  -- 解析数组  如果数组是nil并且不是包含其他的页面
  if (layout.items == nil or #layout.items == 0) and  layout.include == nil then return layoutView; end

  local top = 0;
  local left = 0;
  for i, v in ipairs(layout.items) do
    -- //计算单个cell 宽高
    local w, h;

    if v.type == 'UILayout' then
      UILayout.isAllowStretch = v.isAllowStretch   --（true 可拉伸 false 不可拉伸）
    end


    if v.isEqualToH and v.isEqualToH == 1 then   --isEqualToH 和 isEqualToW 决定暂不使用
      if v.height and v.height ~= 'defult' then
        w = UILayout.calH(v, height, layout.layout);
      else
        w = UILayout.defaultHeight;
      end
    else
      w = UILayout.calW(v, width, layout.layout);
    end

    if v.isEqualToW and v.isEqualToW == 1 then
      h = w ;
    elseif  v.isAllowStretch ~=nil and   v.isAllowStretch == false then  --控件本身不允许拉伸
      h = UILayout.calH(v, height, layout.layout, v.isAllowStretch);
    else
      h = UILayout.calH(v, height, layout.layout,UILayout.isAllowStretch);
    end

    --判断如果是可以拉伸的layout 则其高度加上空白的区域的平均高度
    if #UILayout.infoList > 0 and v.type == 'UILayout' and  v.isAllowStretch then
      for i = 1, #UILayout.infoList do
        --print('wwwwwwwwww===',v.id,UILayout.infoList[i])
        if v.id == UILayout.infoList[i] then
          h = h + UILayout.addHeight ;
        end
      end
    end

    -- 求左边距和上边距
    if layout.layout == 'h' then  --横向布局，默认左边距
      if v.ml then
        left = left + UILayout.getRealityValue(v.ml, width);
    else
      if #layout.items == 1 then --横向布局，且仅有一个view，考虑mr
        if v.mr then
          left = left + width - w - UILayout.getRealityValue(v.mr, width);
      else
        left = left + UILayout.lrInterval;
      end
      else
        left = left + UILayout.lrInterval;
      end
    end

    --    if v.mt == 0 and v.mb == 0 then
    --       h = height ;
    --    end

    if v.mt then  --默认上边距
      top = UILayout.getRealityValue(v.mt, height,UILayout.isAllowStretch);
    else
      if v.mb then --判断是否有下边距，有，父高-view高-mb
        top = height - h - UILayout.getRealityValue(v.mb, height,UILayout.isAllowStretch);
      else
        top = UILayout.tbInterval;
      end
    end
    elseif layout.layout == 'v' then--纵向布局，默认上边距
      if v.ml then
        left = UILayout.getRealityValue(v.ml, width);
    else
      if v.mr then --有右边距
        left = width - w - UILayout.getRealityValue(v.mr, width);
      else
        left = UILayout.lrInterval;
      end
    end

    --   if v.mt == 0 and v.mb == 0 then
    --       h = height ;
    --    end

    if v.mt then
      top = top + UILayout.getRealityValue(v.mt, height,UILayout.isAllowStretch);
    else
      if #layout.items == 1 then --布局仅有一个view
        if v.mb then --判断是否有下边距，有，父高-view高-mb
          top = top + height - h - UILayout.getRealityValue(v.mb, height,UILayout.isAllowStretch);
      else
        top = top + UILayout.tbInterval;
      end
      else
        top = top + UILayout.tbInterval;
      end
    end
    if v.mt and v.mb and i== #layout.items then
      if UILayout.isAllowStretch then
        h = height-top- UILayout.AH(v.mb)
      else
        h = height- top - AW(v.mb)
      end
    end
    else  --原点布局
      if v.y then
        top = UILayout.getRealityValue(v.y, width,UILayout.isAllowStretch);
    else
      --原点布局，x未赋值，默认(0,0)
      top = 0;
    end
    if v.x then
      left = UILayout.getRealityValue(v.x, height);
    else
      --原点布局，y未赋值，默认(0,0)
      left = 0;
    end
    end

    local view = UILayout.genCtrl(  v, w, h,viewCtrl,UILayout.isAllowStretch );
--    print('wwwwwtppppppppppp===',left,top,view.id)
    layoutView:add(view, left, top);

    -- 加 高 宽
    if layout.layout == 'h' then
      left = left + w;
    elseif layout.layout == 'v' then
      top = top + h;
    end

    -- 加 右 下
    if layout.layout == 'h' then
      if v.mr then    --默认没有右边距，默认不添加
        left = left + UILayout.getRealityValue(v.mr, width);
      --      else
      --        left = left + UILayout.lrInterval;
      end
    elseif layout.layout == 'v' then
      if v.mb then
        top = top + UILayout.getRealityValue(v.mb, height,UILayout.isAllowStretch);
      --      else
      --        top = top + UILayout.tbInterval;
      end
    end

  end
  return layoutView;
end

--[[
描述 ：根据type参数判断是何种控件 并且实例化
参数 ： v   --  布局参数
w --控件宽度
h --控件高度
viewCtrl --所在页面索引
返回 ： 无
]]
function UILayout.genCtrl( v, w, h ,viewCtrl,isAllowStretch)
  if  v.items~= nil and  #v.items > 0 then
    --    if v.include ~= nil then
    --      print(' v.include === ', v.include)
    --      local jsoninfo = File.readFile('res/layout/JYLayout.json');
    --      local infol = App.json(jsoninfo);
    --      if infol then
    --        --v.items = infol ;
    --        table.insert(v.items,infol)
    --        --               local aa = App.json(v.items)
    --        --         print('gggggggg====', v.items)
    --      else
    --        print('json222222 不存在~~~~~~~~~~~')
    --        return
    --      end
    --    end
    local layoutView = UILayout.parse( v, w, h,viewCtrl,isAllowStretch );
    return layoutView;
  end
  --print('wwwwwwwww控件======',w,h, v.type)
  if v.type == 'UILayout' then
    --print('UILayout--------------')
    local view = MLView.new():initView(w, h,viewCtrl,v.id);
    if v.color then
      view:setColor(tonumber(v.color));
    end
    if v.image and v.image ~= '' then
      view:setBg(UIImage.imageName(v.image));
    end
    return view;
  end

  if v.type == 'UIHeadView' then
    --print('UILayout--------------')
    local view = UIHeadView.new():init(viewCtrl,'viewCtrl:headView');

    if v.title then
      view:setTitle(v.title);
    end
    if v.bgImage then
      view:setBg(UIImage.imageName(v.bgImage));
    end
    if v.fontColor then
      view.title.fontColor = tonumber(v.fontColor);
    end
    if v.fontHeight then
      view.title.fontHeight = AW(v.fontHeight);
    end
    if v.backImage then
      view.left.bgImage = UIImage.imageName(v.backImage);
    end
    if v.backFocuseImage then
      view.left.focusImage = UIImage.imageName(v.backFocuseImage);
    end

    if v.rightImage then
      view.right.bgImage = UIImage.imageName(v.rightImage);
    end
    if v.rightFocuseImage then
      view.right.focusImage = UIImage.imageName(v.rightFocuseImage);
    end
    view.title:show();
    view.left:show();
    view.right:show();
    return view;
  end

  if v.type == 'UIButton' then
    local button = UIButton.new():init(w, h,viewCtrl,v.id);
    if v.text then
      button.text = v.text;
    end
    if v.fontHeight then
      button.fontHeight = AW(v.fontHeight);
    end
    if v.fontColor then
      button.fontColor = tonumber(v.fontColor);
    end
    if v.fontFocusColor then
      button.fontFocusColor =  tonumber(v.fontFocusColor);
    end
    if v.bgImage then
      button.bgImage = UIImage.imageName(v.bgImage);
    end
    if v.focusImage then
      button.focusImage = UIImage.imageName(v.focusImage);
    end
    --button:show();
    return button;
  end

  if v.type == 'UIImageView' then
    local img = UIImage.imageName('system/noimage.png');
    if  v.image then
      img =  UIImage.imageName(v.image);
    end
    local imgView = UIImageView.new():init(img, w, h,viewCtrl,v.id);
    --imgView:show();
    return imgView;
  end

  if v.type == 'UILabel' then
    --print('UILabel--------------')
    local word = ''
    if v.text then
      word = v.text ;
    end
    local lab = UILabel.new():init(word, w, h,viewCtrl,v.id);
    if v.fontHeight then
      lab.fontHeight = AW(v.fontHeight);
    end
    if v.fontColor then
      lab.fontColor = tonumber(v.fontColor);
    end
    if v.image then
      lab.bgImage  = UIImage.imageName(v.image);
    end
    if v.align then
      lab.align = v.align;
    end
    --lab:show();
    return lab;
  end

  if v.type == 'UITextView' then
    --print('UITextView--------------')
    local word1 = ''
    if v.text then
      word1 = v.text ;
    end
    local textView = UITextView.new():init(word1, w, h,viewCtrl,v.id);
    textView.fontHeight = AW(v.fontHeight);
    textView.fontColor = v.fontColor;
    --textView.align = v.align;
    --textView:show();
    return textView;
  end

  if v.type == 'UIEditText' then
    --print('UIEditText--------------')
    local status= false ;
    if v.isMultiLine  then
      status = true;
    end
    local editView = UIEditText.new():init(w, h, status,viewCtrl,v.id);
    --print('uuuuuu ===',viewCtrl,v.id)
    if v.password  then
      editView:setPassword(true);
    end
    if v.text then
      editView:setText(v.text);
    end
    if v.hintText then
      editView:setHint(v.hintText);
    end
    if v.fontHeight then
      editView:setTextSize(AW(v.fontHeight));
    end
    if v.maxLength then
      editView:setMaxLength(v.maxLength);
    end
    if v.inputType then
      editView:setType(v.inputType);
    end
    if v.bgImage then  --等待添加的参数
      editView.mBgImage = UIImage.imageName(v.bgImage);
    end
    --editView:show();
    return editView;
  end

  if  v.type == 'UICheckBox' then
    local checkBox = UICheckBox.new():init(w, h,viewCtrl,v.id);
    if v.bgImage then  --等待添加的参数
      checkBox.bgImage = UIImage.imageName(v.bgImage);
    end
    if v.focusImage then  --等待添加的参数
      checkBox.focusImage = UIImage.imageName(v.focusImage);
    end
    checkBox.isClick = false;
    --checkBox:show();
    return checkBox;
  end
  --UIGalleryView待测试-----
  if v.type == 'UIGalleryView' then
    local items = {};
    --    for i=1, #v.array do
    --      local imgView = UIImageView.new():init(UIImage.imageName(v.array[i]), w, h,viewCtrl);
    --      imgView:show();
    --      items[#items+1] = imgView;
    --    end
    local galleryView = UIGalleryView.new():init(items, w, h,2,viewCtrl,v.id);
    --galleryView:show();
    return galleryView;
  end


  if v.type == 'UIListView' then
    local isPullUpdate = false;
    if v.isPullUpdate  then
      isPullUpdate = true;
    end
    local isMoreUpdate = false;
    if v.isMoreUpdate then
      isMoreUpdate = true;
    end
    local isDelable = false;
    if v.isDelable  then
      isDelable = true;
    end
    local list = MLListView.new():initListView(w, h,  isPullUpdate, isMoreUpdate, isDelable,viewCtrl,v.id);
    return list;
  end

  if v.type == 'UISplitView' then  --此控件暂时无法使用
  --    local item = {};
  --    for i,v in ipairs(v.array) do
  --      local item1 = UISplitItemView.new():init(v.width, v.height, v.areaW, v.iconType);
  --      item1.bgImage = UIImage.imageName(v.bgImage or 'null.png');
  --      item1.bgSelImage = UIImage.imageName(v.bgSelImage or 'null.png');
  --      item1.itemImage = UIImage.imageName(v.itemImage or 'L-icon1.png');
  --      item1.iteselImage = UIImage.imageName(v.iteselImage or 'L-icon1-1.png');
  --      item1.text = v.text or '';
  --      item1.fontColor = v.fontColor or 0x000000;
  --      item1.fontFocusColor = v.fontFocusColor or 0xffffff;
  --      item1.fontHeight = v.fontHeight or AW(12);
  --      item1.itemImageWidth = v.itemImageWidth or AW(30);
  --      item1.itemImageHeight = v.itemImageHeight or AW(30);
  --      item1:show();
  --      item[#item + 1] = item1;
  --    end

  --    if #item == 0 then
  --      return MLView.new():initView();
  --    end
  --    local tabbar = UISplitView.new():init(w, h, AW(v.leftViewWidth), nil, viewCtrl,v.id);
  --    tabbar.mItemsRootView:setColor(0x00428e);
  --    tabbar:setBarItemView(item);
  --    return tabbar;
  end

  if v.type == 'UIRadioButton' then
    local radio = UIRadioButton.new():init(w, h, viewCtrl,v.id);
    if v.bgImage then
      radio.bgImage = UIImage.imageName(v.bgImage);
    end
    if v.selImage then
      radio.selImage = UIImage.imageName(v.selImage);
    end
    if v.isSel then
      radio.mIsSel = true;
    end
    --radio:show();
    return radio;
  end

  if v.type == 'UISlideView' then
    local curPos = 0 ;
    if  v.curPos then
      curPos = v.curPos;
    end
    local slideView = UISlideView.new():init(curPos,w, viewCtrl,v.id);
    if v.bgImage then
      slideView.bgImage =  UIImage.imageName(v.bgImage);
    end
    if v.barImage then
      slideView.barImage =  UIImage.imageName(v.barImage);
    end
    if v.fullImage then
      slideView.fullImage =  UIImage.imageName(v.fullImage);
    end
    --slideView:show();
    return slideView;
  end

  if v.type == 'UITabBarView' then
    local isTop = false ;
    local itemsHeight = 45 ;
    if  v.isTop then
      isTop = v.isTop;
    end
    if  v.itemsHeight then
      itemsHeight = v.itemsHeight;
    end
    local tabView = UITabBarView.new():init(w, h, AW(itemsHeight), isTop, viewCtrl, v.id)
    return tabView;
  end

  --UIScrollView 待测试  有点问题
  if v.type == 'UIScrollView' then
    local isHorizontal = false
    if  v.isHorizontal then
      isHorizontal = v.isHorizontal;
    end
    local scrollView = UIScrollView.new():init( w, h, isHorizontal, viewCtrl, v.id )
    return scrollView;
  end

  if v.type == 'UIZoomImageView' then
    local src = '';
    if v.image then
      src = 'res/image/'..v.image ;
    end
    local view = UIZoomImageView.new():init(w, h, src,viewCtrl,v.id);
    return view;
  end

  if v.type == 'UIWebImageView' then
    local src = '';
    if v.src then
      src = v.src
    end
    local webImageView = UIWebImageView.new():init(w, h, src, nil or  UIImage.imageName(v.image),viewCtrl,v.id);
    return webImageView;
  end

  if v.type == 'UIPdfView' then
    local src = '';
    if v.src then
      src = v.src
    end
    local pdfView = UIPdfView.new():init(w,h,src,viewCtrl,v.id)
    return pdfView;
  end

  if v.type == 'UIWebView' then
    local webview = UIWebView.new():init(w, h,viewCtrl,v.id);
    if v.url then
      webview:loadUrl(v.url or 'http://www.baidu.com');
    elseif  v.html then
      webview:loadHtml(v.html);
    else
    end
    return webview;
  end

  if v.type == 'UIVideoView' then
    local videoview = UIVideoView.new():init(w, h,viewCtrl,v.id);
    videoview:setColor(UIColor.COLOR_GRAY);
    return videoview;
  end

end
